package net.jeeshop.web.action.front.pay;

import net.jeeshop.alipay.util.AlipayNotify;
import net.jeeshop.core.system.bean.User;
import net.jeeshop.services.common.LfbRecord;
import net.jeeshop.services.front.account.AccountService;
import net.jeeshop.services.front.account.bean.Account;
import net.jeeshop.services.front.order.OrderService;
import net.jeeshop.services.front.order.bean.Order;
import net.jeeshop.services.front.orderdetail.OrderdetailService;
import net.jeeshop.services.front.orderdetail.bean.Orderdetail;
import net.jeeshop.services.front.orderpay.OrderpayService;
import net.jeeshop.services.front.product.ProductService;
import net.jeeshop.services.front.product.bean.Product;
import net.jeeshop.services.front.shopRule.ShopRuleService;
import net.jeeshop.services.front.shopRule.bean.ShopRule;
import net.jeeshop.services.manage.system.impl.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created by douzy on 16/8/18.
 */
@Controller("alipayController")
@RequestMapping("alipay")
public class AlipayNotifyController {

    @Autowired
    OrderService orderService;
    @Autowired
    OrderpayService orderpayService;
    @Autowired
    OrderdetailService orderdetailService;
    @Autowired
    ProductService productService;
    @Autowired
    private UserService userService;
    @Autowired
    private ShopRuleService shopRuleService;
    @Autowired
    private AccountService accountService;

    /**
     * 支付宝异步回调1 1
     *
     * @param request
     * @param response
     * @return
     * @throws Exception
     */
    @RequestMapping("/notify")
    @ResponseBody
    public void notify(HttpServletRequest request, HttpServletResponse response) throws Exception {


        System.out.println("********支付宝开始回调啦*************");
        Map<String, String> params = new HashMap<String, String>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk");
            params.put(name, valueStr);
        }

        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)//
        //商户订单号

        String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("out_trade_no:" + out_trade_no);
        //支付宝交易号

        String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("trade_no:" + trade_no);
        //交易状态
        String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"), "UTF-8");
        System.out.println("trade_status:" + trade_status);
        //获取支付宝的通知返回参数，可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)//

        if (AlipayNotify.verify(params)) {//验证成功
            //////////////////////////////////////////////////////////////////////////////////////////
            //请在这里加上商户的业务逻辑程序代码

            //——请根据您的业务逻辑来编写程序（以下代码仅作参考）——

            if (trade_status.equals("TRADE_FINISHED") || trade_status.equals("TRADE_SUCCESS")) {
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
                Order order = orderService.selectOneByOrderNo(out_trade_no);

                //订单状态为未审核 且 支付状态为n  表示该订单未被处理
                if (order.getStatus().equals(net.jeeshop.services.manage.order.bean.Order.order_status_init) && order.getPaystatus().equals(net.jeeshop.services.manage.order.bean.Order.order_paystatus_n)) {

                    net.jeeshop.services.front.orderdetail.bean.Orderdetail orderdetailParm = new net.jeeshop.services.front.orderdetail.bean.Orderdetail();
                    orderdetailParm.setOrderID(Integer.valueOf(order.getId()));

                    Orderdetail orderdetail = orderdetailService.selectOneByOrderId(orderdetailParm);

                    if (orderdetail != null) {
                        Integer proId = orderdetail.getProductID();

                        Product product = productService.selectById(proId.toString());

                        if (product != null) {
                            User suser = new User();
                            suser.setUsername(product.getCreateAccount());
                            User user = userService.selectOne(suser);
                            if (user != null) {
                                ShopRule rule = new ShopRule();
                                rule.setUserid(user.getId());
                                ShopRule shopRule = shopRuleService.selectOne(rule);
                                if (shopRule != null) {
                                    Account saccount = new Account();
                                    saccount.setAccount(order.getAccount());
                                    Account account = accountService.selectOne(saccount);

                                    double dk = Double.parseDouble(order.getAmount());
                                    if (account.getLfb() < Double.valueOf(dk * shopRule.getDkration()).intValue()) {
                                        account.setLfb(0);
                                    } else {
                                        account.setLfb(account.getLfb() - Double.valueOf(dk * shopRule.getDkration()).intValue());
                                    }

                                    account.setLfb(account.getLfb() + Double.valueOf(dk * shopRule.getFxration()).intValue());
                                    accountService.update(account);


                                    LfbRecord lfbRecord = new LfbRecord();
                                    lfbRecord.setUserId(account.getId());
                                    lfbRecord.setType(1);
                                    lfbRecord.setCnt(Double.valueOf(dk * shopRule.getFxration()).intValue());
                                    lfbRecord.setRecord("购买商品" + order.getOrderNo() + "获赠" + Double.valueOf(dk * shopRule.getFxration()).intValue() + "龙凤币");
                                    accountService.insertLfbRecord(lfbRecord);


                                    lfbRecord = new LfbRecord();
                                    lfbRecord.setUserId(account.getId());
                                    lfbRecord.setType(1);
                                    lfbRecord.setCnt(Double.valueOf(dk * shopRule.getDkration()).intValue());
                                    lfbRecord.setRecord("购买商品" + order.getOrderNo() + "花费" + Double.valueOf(dk * shopRule.getDkration()).intValue() + "龙凤币");
                                    accountService.insertLfbRecord(lfbRecord);


                                }

                            }


                            product.setStock(product.getStock() - order.getQuantity()); //商品库存减
                            productService.update(product);
                        }
                    }

                    order.setPaystatus(net.jeeshop.services.front.order.bean.Order.order_paystatus_y);
                    orderService.update(order); //更新订单表 支付状态

//                    net.jeeshop.services.food.orderpay.bean.Orderpay orderpayParm=new net.jeeshop.services.food.orderpay.bean.Orderpay();
//                    orderpayParm.setOrderid(order.getId());
                    net.jeeshop.services.front.orderpay.bean.Orderpay orderpay = orderpayService.selectOneByOrderId(order.getId());

                    orderpay.setPaystatus(net.jeeshop.services.front.order.bean.Order.order_paystatus_y);
                    orderpay.setTradeNo(trade_no);
                    orderpayService.update(orderpay);//更新支付记录表 支付状态及 支付宝交易号

                    //——请根据您的业务逻辑来编写程序（以上代码仅作参考）——

                    response.getWriter().println("success");    //请不要修改或删除
                } else
                    response.getWriter().println("fail");

            }
            //判断该笔订单是否在商户网站中已经做过处理
            //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
            //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的
            //如果有做过处理，不执行商户的业务程序

            //注意：
            //付款完成后，支付宝系统发送该交易状态通知

            //////////////////////////////////////////////////////////////////////////////////////////
        } else {//验证失败
            response.getWriter().println("fail");
        }
    }

}
